/**
 * Created by arter on 2015/12/7.
 */

// ajax get请求
/**
 * <a href="#" class="confirm ajax-get text-info" >删除</a></td>
 *
 */
window.confirm = function(message, callback) {
  $('#bootstrap-confirm-box-modal').data('confirm-yes', false);
  if ($('#bootstrap-confirm-box-modal').length == 0) {
    $('body').append('<div id="bootstrap-confirm-box-modal" class="modal fade">\
          <div class="modal-dialog modal-dialog-centered modal-sm" style="width:250px;">\
              <div class="modal-content">\
                  <div class="modal-body text-center"><p style="font-size:20px"></p></div>\
                  <div class="modal-footer justify-content-center" style="border-top:0;padding: 10px;">\
                      <a href="#" class="btn btn-primary">确认</a>\
                      <a href="#" data-dismiss="modal" class="btn btn-light">取消</a>\
                  </div>\
              </div>\
          </div>\
      </div>');
    $('#bootstrap-confirm-box-modal .modal-footer .btn-primary').on('click', function() {
      $('#bootstrap-confirm-box-modal').data('confirm-yes', true);
      $('#bootstrap-confirm-box-modal').modal('hide');
      return false;
    });
    $('#bootstrap-confirm-box-modal').on('hide.bs.modal', function() {
      if (callback) callback($('#bootstrap-confirm-box-modal').data('confirm-yes'));
    });
  }
  $('#bootstrap-confirm-box-modal .modal-body p').text(message || '');
  $('#bootstrap-confirm-box-modal').modal('show');
};
$(document).on('click', '.ajax-get', function() {
  var target;
  var that = this;
  if ($(this).hasClass('confirm')) {
    if (!confirm('确认要执行提交操作吗?')) {
      return false;
    }
  }
  if ((target = $(this).attr('href')) || (target = $(this).attr('url'))) {
    $.get(target).success(function(data) {
      if (data.errno == 0) {
        if (data.data.url) {
          toastr.success(data.data.name + ' 页面即将自动跳转~');
        } else {
          toastr.success(data.data.name);
        }
        setTimeout(function() {
          if (data.data.url) {
            location.href = data.data.url;
          } else if ($(that).hasClass('no-refresh')) {
            toastr.clear();
          } else {
            location.reload();
          }
        }, 1500);
      } else {
        toastr.error(data.errmsg);
        setTimeout(function() {
          if (data.data) {
            location.href = data.data;
          } else {
            toastr.clear();
          }
        }, 1500);
      }
    });
  }
  return false;
});

// todo
$('.todo').click(function(e) {
  e.preventDefault();
  toastr.info('功能开发中，敬请期待...');
});
$('.cw-cf').click(function() {
  var href = $(this).attr('href');
  console.log(href);
  swal({
    title: '确定清空回收站?',
    text: '清空后不可恢复，请谨慎操作!',
    html: true,
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: '确定!',
    cancelButtonText: '算了',
    closeOnConfirm: false }, function() {
    $.get(href).success(function(data) {
      console.log(data);
      if (data.errno == 0) {
        swal({title: data.data.name, text: '', type: 'success'}, function() {
          location.reload();
        });
      } else {

      }
    });
  });
  return false;
});
/**
 * ajax post submit请求
 * <form class = "form-horizontal">
 * <button target-form="form-horizontal" type="submit" class="ajax-post">确定</button>
 * confirm,
 */
const keyNameMap = {
  yewuleixing: '信息类型',
  taxes: '发票税率',
  fukuanjine: '付款金额',
  content: '内容',
  nickname: '昵称',
  oldpassword: '旧密码',
  repassword: '确认密码',
  real_name: '姓名',
  user_code: '身份证号',
  mobile: '手机号码',
  gsmc: '公司名称',
  sfzzmpic: '身份证正面',
  sfzfmpic: '身份证反面',
  yyzzpic: '营业执照',
  khxkzpic: '开户许可证',
  sysnumber: '验证码',
  username: '手机号',
  password: '密码',
  xinxileixing: '信息类型',
  xinxibiaoti: '信息标题',
  shangpingleibie: '商品类别',
  jiage: '商品价格',
  shangpingshuliang: '预计数量',
  zongjia: '预计货款',
  youxiaoqi: '有效期',
  diqu: '所在地区',
  suozaiweizhi: '详细位置',
  chuchenglv: '出成率',
  leirongmiaoshu: '商品描述',
  persent: '付款比例',
  duifanggsmc: ' 公司(商户)名称',
  duifangrealname: ' 联系人',
  duifangmobile: ' 联系电话',
  duifangid: '对方信息'
};
function ajaxpost() {
  var target, query, form;
  var target_form = $(this).attr('target-form');
  var that = this;
  var nead_confirm = false;
  if (($(this).attr('type') == 'submit') || (target = $(this).attr('href')) || ($(this).attr('act') == 'ajax-post') || (target = $(this).attr('url'))) {
    form = $('.' + target_form);
    if ($(this).attr('hide-data') === 'true') { // 无数据时也可以使用的功能
      form = $('.hide-data');
      query = form.serialize();
    } else if (form.get(0) == undefined) {
      return false;
    } else if (form.get(0).nodeName == 'FORM') {
      // 表单验证
      if ($('.' + target_form + '[data-validate="parsley"]').length > 0) {
        $('.' + target_form + '[data-validate="parsley"]').parsley().on('field:error', function() {
          toastr.error('必填项:' + (keyNameMap[this.$element[0].name] || this.$element[0].name));
        });
        $('.' + target_form + '[data-validate="parsley"]').parsley().validate();
        $('.' + target_form + '[data-validate="parsley"]').parsley().off('field:error');
        if ($('.' + target_form + '[data-validate="parsley"]').parsley().isValid() !== true) {
          return false;
        }
      }
      if ($(this).attr('url') !== undefined) {
        target = $(this).attr('url');
      } else {
        target = form.get(0).action;
      }
      query = form.serialize();
    } else if (form.get(0).nodeName == 'INPUT' || form.get(0).nodeName == 'SELECT' || form.get(0).nodeName == 'TEXTAREA') {
      form.each(function(k, v) {
        if (v.type == 'checkbox' && v.checked == true) {
          nead_confirm = true;
        }
      });
      if ($(form).hasClass('sort')) {
        var arr = [];
        form.each(function(k, v) {
          var obj = {};
          obj.id = $(v).attr('data-id');
          obj.sort = $(v).val();
          arr.push(obj);
        });
        query = {sort: JSON.stringify(arr)};
      } else {
        // alert(1)
        query = form.serialize();
        // alert(query)
      }
    } else {
      query = form.find('input,select,textarea').serialize();
    }
    $(that).addClass('disabled').attr('autocomplete', 'off').prop('disabled', true);
    if ($(this).hasClass('confirm')) {
      var message = $(this).attr('message') || '确认要执行提交操作吗?';
      confirm(message, function(value) {
        if (value) {
          $.post(target, query, function(data) {
            if (data.errno == 0) {
              if (data.data.url) {
                toastr.success(data.data.name + ' 页面即将自动跳转~');
              } else {
                toastr.success(data.data.name);
              }
              setTimeout(function() {
                $(that).removeClass('disabled').prop('disabled', false);
                if (data.data.url) {
                  location.href = data.data.url;
                } else if ($(that).hasClass('no-refresh')) {
                  toastr.clear();
                } else {
                  location.reload();
                }
              }, 1500);
            } else {
              if (data.errmsg == 'validate error') {
                $.each(data.data, function(i, n) {
                  toastr.error(n);
                });
              // return false;
              } else {
                toastr.error(data.errmsg);
              }

              setTimeout(function() {
                $(that).removeClass('disabled').prop('disabled', false);
                if (!$.isPlainObject(data.data) && data.data) {
                  location.href = data.data;
                } else {
                  toastr.clear();
                }
              }, 1500);
            }
          }).fail(function() {
            toastr.error('系统出错，请重试');
            setTimeout(function() {
              $(that).removeClass('disabled').prop('disabled', false);
              toastr.clear();
            }, 1500);
          });
        } else {
          $(that).removeClass('disabled').prop('disabled', false);
        }
      });
    } else {
      $.post(target, query, function(data) {
        if (data.errno == 0) {
          if (data.data.url) {
            toastr.success(data.data.name + ' 页面即将自动跳转~');
          } else {
            toastr.success(data.data.name);
          }
          setTimeout(function() {
            $(that).removeClass('disabled').prop('disabled', false);
            if (data.data.url) {
              location.href = data.data.url;
            } else if ($(that).hasClass('no-refresh')) {
              toastr.clear();
            } else {
              location.reload();
            }
          }, 1500);
        } else {
          if (data.errmsg == 'validate error') {
            $.each(data.data, function(i, n) {
              toastr.error(n);
            });
            // return false;
          } else {
            toastr.error(data.errmsg);
          }

          setTimeout(function() {
            $(that).removeClass('disabled').prop('disabled', false);
            if (!$.isPlainObject(data.data) && data.data) {
              location.href = data.data;
            } else {
              toastr.clear();
            }
          }, 1500);
        }
      }).fail(function() {
        toastr.error('系统出错，请重试');
        setTimeout(function() {
          $(that).removeClass('disabled').prop('disabled', false);
          toastr.clear();
        }, 1500);
      });
    }
  }
  return false;
}
$(document).on('click', '.ajax-post', ajaxpost);
$(document).on('click', '[act="ajax-post"]', ajaxpost);
$(document).on('click', '[data-toggle="ajaxModal"]', function(e) {
  $('#ajaxModal').remove();
  e.preventDefault();
  var that = this;
  $(that).addClass('disabled').prop('disabled', true);
  var target_form = $(this).attr('target-form');
  var form = $('.' + target_form);
  var query = form.find('input,select,textarea').serialize();
  // 表单验证
  if ($('.' + target_form + '[data-validate="parsley"]').length > 0) {
    $('.' + target_form + '[data-validate="parsley"]').parsley().on('field:error', function() {
      toastr.error('必填项:' + (keyNameMap[this.$element[0].name] || this.$element[0].name));
    });
    $('.' + target_form + '[data-validate="parsley"]').parsley().validate();
    $('.' + target_form + '[data-validate="parsley"]').parsley().off('field:error');
    if ($('.' + target_form + '[data-validate="parsley"]').parsley().isValid() !== true) {
      $(that).removeClass('disabled').prop('disabled', false); $(that).removeClass('disabled').prop('disabled', false);
      return false;
    }
  }
  var $this = $(this),
    $remote = ($this.data('remote') || $this.attr('href')) + '?' + query,
    $modal = $('<div class="modal fade" id="ajaxModal"><div class="modal-body"></div></div>');
  $('body').append($modal);
  $modal.load($remote, function() {
    $modal.modal();
    $('[aria-label="Close"]').on('click', function(e) {
      $(that).removeClass('disabled').prop('disabled', false);
      $modal.modal('hide');
    });
    $modal.on('hidden.bs.modal', function(e) {
      $(that).removeClass('disabled').prop('disabled', false);
    });
  });
});

$(document).on('click', '[data-toggle="lightbox"]', function(event) {
  event.preventDefault();
  $(this).ekkoLightbox();
});
/** ************************************************************** **/
var _arr 	= {};
function loadScript(scriptName, callback) {
  if (!_arr[scriptName]) {
    _arr[scriptName] = true;

    var body 		= document.getElementsByTagName('body')[0];
    var script 		= document.createElement('script');
    script.type 	= 'text/javascript';
    script.src 		= scriptName;

    // then bind the event to the callback function
    // there are several events for cross browser compatibility
    // script.onreadystatechange = callback;
    script.onload = callback;

    // fire the loading
    body.appendChild(script);
  } else if (callback) {
    callback();
  }
};

/**
/** 08. Lazy Load
	<img class="lazy" data-original="img/example.jpg" width="765" height="574">
 **************************************************************** **/
var plugin_path = '/static/assets/plugins/';
function _lazyload() {
  var _container = jQuery('img.lazy');

  if (_container.length > 0) {
    loadScript(plugin_path + 'lazyload/jquery.lazyload.min.js', function() {
      if (jQuery().lazyload) {
        _container.each(function() {
          var _t 		= jQuery(this),
            _effect = _t.attr('data-effect') || 'fadeIn';

          _t.lazyload({
            effect: _effect
          });
        });
      }
    });
  }
}
_lazyload();
function sendSMS(e, obj, key, form) {
  e.preventDefault();
  var reg = /^1[3|4|5|6|7|8|9]\d{9}$/g;
  var countdown = 60;
  var mobile = '';
  if (form) {
    mobile = $(form + " input[name='" + key + "']").val();
  } else {
    mobile = $("input[name='" + key + "']").val();
  }
  if (!reg.test(mobile)) {
    toastr.error('请先输入手机号!');
    return false;
  }
  $.post(
    '/ws/common/sendsms',
    {
      mobile: mobile
    },
    function(data) {
      settime(obj);
    }
  );
  function settime(obj) {
    if (countdown == 0) {
      obj.removeAttribute('disabled');
      obj.innerHTML = '获取验证码';
      countdown = 60;
      return false;
    } else {
      obj.setAttribute('disabled', true);
      obj.innerHTML = '重新发送(' + countdown + ')';
      countdown--;
    }
    setTimeout(function() {
      settime(obj);
    }
      , 1000);
  }
  return false;
}
function urlGoto(url) {
  var stack = JSON.parse(sessionStorage.getItem('historyStack'));
  stack ? '' : stack = [];
  var locationP = window.location.href.split('#')[0];
  stack.push(locationP + (locationP.indexOf('search') !== -1 ? '&keyword=' + $('#keyword').val() : ''));
  sessionStorage.setItem('historyStack', JSON.stringify(stack));
  location.href = url;
}

function historyGoBack(url) {
// 从sessionStorage获取数据
  var stack = JSON.parse(sessionStorage.getItem('historyStack'));
  stack ? '' : stack = [];
  var i = stack.pop(); // stack is now [2]
  // 保存数据到sessionStorage
  sessionStorage.setItem('historyStack', JSON.stringify(stack));
  console.log(i || url);
  location.href = i || url;
}
jQuery.extend({
  getQueryParameters: function(str) {
    return (str || document.location.search).replace(/(^\?)/, '').split('&').map(function(n) { return n = n.split('='), this[n[0]] = n[1], this }.bind({}))[0];
  }
});
function quertString(obj) {
  return Object.keys(obj).map(function(key) {
    if (key) return key + '=' + obj[key];
  }).join('&');
}

function gotoPage() {
  var page = $('[name="pagenum"]')[0].value;
  if (page > 0) {
    var queryParams = $.getQueryParameters();
    queryParams.page = page > totalPages ? totalPages : page;
    window.location.href = location.pathname + '?' + quertString(queryParams);
  }
}

var ad = new Swiper('.ad-swiper-container', {
  centeredSlides: true,
  autoplay: {
    delay: 2500,
    disableOnInteraction: false
  },
  pagination: {
    el: '.swiper-pagination',
    clickable: true
  }
});

var galleryThumbs = new Swiper('.gallery-thumbs', {
  spaceBetween: 10,
  slidesPerView: 4,
  freeMode: false,
  centeredSlides: true,
  watchSlidesVisibility: true,
  watchSlidesProgress: true,
  autoplay: {
    delay: 2500,
    disableOnInteraction: true
  }
});
var galleryTop = new Swiper('.gallery-top', {
  autoplay: {
    delay: 2500,
    disableOnInteraction: true
  },
  zoom: true,
  freeMode: false,
  thumbs: {
    swiper: galleryThumbs
  }
});

$('.swiper-container').hover(function() {
  galleryThumbs.autoplay.stop();
  galleryTop.autoplay.stop();
}, function() {
  galleryThumbs.autoplay.start();
  galleryTop.autoplay.start();
});

$('.gallery-thumbs .swiper-slide').hover(function() {
  var index = $('.gallery-thumbs .swiper-slide').index($(this)[0]);
  galleryTop.slideTo(index);
}, function() {
  console.log('hover out');
});

var inputs = document.getElementsByTagName('input');
for (var index = 0; index < inputs.length; ++index) {
  (function(index) {
    var element = inputs[index];
    console.log(element);
    element.addEventListener('invalid', function() {
      if (element.value === '') {
        element.setCustomValidity('请输入');
      }
    });
  })(index);
}
